package org.tgcloud.group.service.manager;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.tgcloud.group.core.*;
import org.tgcloud.group.core.ExportUtils.ExcelUtils;
import org.tgcloud.group.entity.SysLabelValue;
import org.tgcloud.group.repository.*;
import org.tgcloud.group.web.controller.dto.sys.InitIndexListDTO;
import org.tgcloud.group.web.controller.dto.sys.SysLabelListDTO;
import org.tgcloud.group.web.controller.dto.sys.SysLabelValueListDTO;
import org.tgcloud.group.web.controller.req.sysLabel.*;

import java.io.File;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author: zhy
 * @create: 2023-06-27 10:41
 * @description:
 */
@Service
public class SysManageService {


    @Value("${upload.file.path}")
    private String filePath;

//    private static final String contractURL = "https://checkorder.mejour.cn/contract";

    @Autowired
    private SysLabelValueMapper sysLabelValueMapper;

    @Autowired
    private SysLabelMapper sysLabelMapper;

    @Autowired
    private MjBusinessPersonMapper businessPersonMapper;

    @Autowired
    private SysAreaCityMapper cityMapper;

    @Autowired
    private SysAreaProvinceMapper provinceMapper;

    @Autowired
    private SysAreaDistrictMapper districtMapper;

    public APPResultMessage getSysLabelValueManageList(SysLabelIdReq req) {
        if (req.getPageNum() != null && req.getPageSize() != null){
            PageHelper.startPage(req.getPageNum(), req.getPageSize());
            List<SysLabelValueListDTO> listDTOS = sysLabelValueMapper.selectListBySysLabelId(req.getSysLabelId(),req.getKeyword(), req.getShowId() != null? req.getShowId(): 0);
            PageInfo<SysLabelValueListDTO> tables = new PageInfo<>(listDTOS);
            ResultMessage resultMessage = ResultMessage.builder().setList(tables.getList()).setAllPageNumber(tables.getPages()).setCount(tables.getTotal());
            APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
            successMessage.setResult(resultMessage);
            return successMessage;
        }else {
            if (req.getSysLabelId() != null){
                List<SysLabelValueListDTO> listDTOS = sysLabelValueMapper.selectListBySysLabelId(req.getSysLabelId(),req.getKeyword(),req.getShowId() != null? req.getShowId(): 0);
                String key = "sys_" + req.getSysLabelId();
                if (!RedisUtil.existKey(key)){
                    RedisUtil.setCacheList(key, listDTOS);
                }
                ResultMessage resultMessage = ResultMessage.builder().setList(listDTOS);
                APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
                successMessage.setResult(resultMessage);
                return successMessage;
            }else {
                String[] split = req.getSysLabelIds().split(",");
                Map<Integer, List<SysLabelValueListDTO>> map = new HashMap();
                for (String id : split){
                    Integer labelId = Integer.valueOf(id);
                    List<SysLabelValueListDTO> listDTOS = new ArrayList<>();
                    if (labelId == 7){
                        listDTOS = businessPersonMapper.selectListBySysLabelId(req.getKeyword());
                        map.put(Integer.valueOf(id), listDTOS);
                    }else {
                        listDTOS = sysLabelValueMapper.selectListBySysLabelId(labelId,req.getKeyword(),req.getShowId() != null? req.getShowId(): 0);
                        map.put(Integer.valueOf(id), listDTOS);
                    }
                    String key = "sys_" + id;
                    if (!RedisUtil.existKey(key)){
                        RedisUtil.setCacheList(key, listDTOS);
                    }
                }
                ResultMessage resultMessage = ResultMessage.builder().setData(map);
                APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
                successMessage.setResult(resultMessage);
                return successMessage;
            }
        }
    }

    public APPResultMessage selectAllGroup(Integer targetId) {
        System.out.println(targetId);
        System.out.println("++++++++++++++++++++");
        List<SysLabelValueListDTO> sysLabelValueListDTOS = sysLabelValueMapper.selectAllGroup(targetId);
        ResultMessage resultMessage = ResultMessage.builder().setList(sysLabelValueListDTOS);
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        successMessage.setResult(resultMessage);
        return successMessage;
    }


        public APPResultMessage<Object, SysLabelListDTO> getSysLabelManageList(SysLabelPageReq req) {
        if (req.getPageNum() != null && req.getPageSize() != null){
            PageHelper.startPage(req.getPageNum(), req.getPageSize());
            List<SysLabelListDTO> listDTOS = sysLabelMapper.selectList();
            PageInfo<SysLabelListDTO> tables = new PageInfo<>(listDTOS);
            ResultMessage resultMessage = ResultMessage.builder().setList(tables.getList()).setAllPageNumber(tables.getPages()).setCount(tables.getTotal());
            APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
            successMessage.setResult(resultMessage);
            return successMessage;
        }else {
            List<SysLabelListDTO> listDTOS = sysLabelMapper.selectList();
            ResultMessage resultMessage = ResultMessage.builder().setList(listDTOS);
            APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
            successMessage.setResult(resultMessage);
            return successMessage;
        }
    }

    public APPResultMessage<Object, List> doAddSysLabelValue(SysLabelValueAddReq req) {
        long a = System.currentTimeMillis();
        System.out.println("开始时间===》"+a);
        SysLabelValue labelValue = sysLabelValueMapper.selectValueBySysIdAndName(req.getSysLabelId(), req.getSysValueName());
        if (labelValue != null){
            return new APPResultMessage<>(5001, "该值已添加过，请重新赋值");
        }
        SysLabelValue sysLabelValue = new SysLabelValue();
        sysLabelValue.setSysLabelId(req.getSysLabelId());
        sysLabelValue.setSysValueName(req.getSysValueName());
        sysLabelValue.setCreateTime(new Date());
        sysLabelValue.setStatus((short) 1);
        sysLabelValue.setDesc(req.getDesc());
        if (req.getShowId() != null){
            sysLabelValue.setPId(req.getShowId());
        }
        if (req.getChildFlag() != null){
            sysLabelValue.setIsHaschild(req.getChildFlag());
        } else {
            sysLabelValue.setIsHaschild(0);
        }
        sysLabelValueMapper.insertSelective(sysLabelValue);
        String key = "sys_" + req.getSysLabelId();
        RedisUtil.deleteObject(key);
//        List<SysLabelValueListDTO> sysLabelValues = new ArrayList<>();
//        if (RedisUtil.existKey(key)){
//            sysLabelValues = RedisUtil.getCacheList(key);
//        }
//        SysLabelValueListDTO sysLabelValueListDTO = new SysLabelValueListDTO();
//        BeanUtils.copyProperties(sysLabelValue, sysLabelValueListDTO);
//        sysLabelValues.add(sysLabelValueListDTO);
//        RedisUtil.setCacheList(key, sysLabelValues);
        long b = System.currentTimeMillis();
        System.out.println("结束时间===》"+b);
        System.out.println("时间差===》"+ (b-a));
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage<Object, List> doEditSysLabelValue(SysLabelValueEditReq req) {
        SysLabelValue labelValue = sysLabelValueMapper.selectValueBySysIdAndNameAndId(req.getSysLabelId(), req.getSysValueName(),req.getValueId());
        if (labelValue != null){
            return new APPResultMessage<>(5001, "该值已添加过，请重新赋值");
        }
        SysLabelValue sysLabelValue = new SysLabelValue();
        sysLabelValue.setId(req.getValueId());
        sysLabelValue.setSysValueName(req.getSysValueName());
        sysLabelValue.setDesc(req.getDesc());
        sysLabelValueMapper.updateByPrimaryKeySelective(sysLabelValue);
        String key = "sys_" + req.getSysLabelId();
        RedisUtil.deleteObject(key);
//        List<SysLabelValueListDTO> sysLabelValues = new ArrayList<>();
//        if (RedisUtil.existKey(key)){
//            sysLabelValues = RedisUtil.getCacheList(key);
//        }
//        SysLabelValueListDTO sysLabelValueListDTO = new SysLabelValueListDTO();
//        BeanUtils.copyProperties(sysLabelValue, sysLabelValueListDTO);
//        List<SysLabelValueListDTO> collect = sysLabelValues.stream().map(dto -> dto.getId().equals(req.getValueId()) ? sysLabelValueListDTO : dto).collect(Collectors.toList());
//        RedisUtil.setCacheList(key, collect);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage doDelSysLabelValue(SysLabelIdsReq req) {
        String sysLabelIds = req.getSysLabelIds();
        String[] split = sysLabelIds.split(",");
        for (String id : split){
            String key = "sys_" + id;

            if (RedisUtil.existKey(key)){
                RedisUtil.deleteObject(key);
            }
        }
        sysLabelValueMapper.updateDelStatusByIds(split);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage doUploadFile(MultipartFile file){
        try {
            if (file.isEmpty()) {
                return APPResultMessage.MISS_PARAMETER();
            }
            { // 本地上传
                String fileName = file.getOriginalFilename();  // 文件名
                String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
                fileName = StringUtil.generateOrderId() + suffixName; // 新文件名
                String path = ExcelUtils.doViewFilePath(filePath) + File.separator + fileName;
                File dest = new File(path);
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();
                }
                file.transferTo(dest);
                String finalPath = ExcelUtils.doViewFilePath(GlobalStatic.contractURL) + File.separator + fileName;
                APPResultMessage message = APPResultMessage.getSuccessMessage();
                message.setResult(ResultMessage.builder().setData(finalPath));
                return message;
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
            return APPResultMessage.getErrorMessage(e.getMessage());
        }
    }


    public APPResultMessage selectProvince() {
        return APPResultMessage.getSuccessMessage(ResultMessage.builder().setList(provinceMapper.selectList()));
    }

    public APPResultMessage selectCity(String province) {
        ArrayList<String> strings = null;
        if (StringUtil.isNotBlank(province)) {
            strings = Lists.newArrayList(province);
        }
        List<String> list = cityMapper.selectListByProvinceList(strings);

        // 初始化列表
        List<InitIndexListDTO> dtos = initList();

        if (!BeanUtil.isNullList(list)) {
            for (String str : list) {
                String pinYin = StringUtil.toPinYin(str);

                // 获取对应首字母
                Optional<InitIndexListDTO> cartOptional = dtos.stream().filter(item -> item.getInitials().equals(pinYin)).findFirst();

                if (cartOptional.isPresent()) {
                    InitIndexListDTO dto = cartOptional.get();
                    // 填充城市
                    List<String> citys = dto.getList();
                    if (BeanUtil.isNullList(citys)) {
                        citys = new ArrayList<>();
                    }
                    citys.add(str);
                    dto.setList(citys);
                }
            }
        }
        ResultMessage resultMessage = ResultMessage.builder().setList(dtos);
        resultMessage.setData(list);
        return APPResultMessage.getSuccessMessage(resultMessage);
    }

    /**
     * 初始化城市列表
     *
     * @return
     */
    private List<InitIndexListDTO> initList() {
        String[] charList = StringUtil.charList;
        List<InitIndexListDTO> list = new ArrayList<>();

        for (String str : charList) {
            InitIndexListDTO dto = new InitIndexListDTO();
            dto.setInitials(str);
            list.add(dto);
        }
        return list;
    }



    public APPResultMessage selectDistrict(String city) {
        return APPResultMessage.getSuccessMessage(ResultMessage.builder().setList(districtMapper.selectListByCityList(Lists.newArrayList(city))));
    }

    public APPResultMessage getAllArea() {
        return APPResultMessage.getSuccessMessage(ResultMessage.builder().setList(sysLabelValueMapper.selectAllArea()));
    }

    public String doReadOneSysLabelValue(Integer id){
        String key = "sys_readOne_" + id;
        String returnValue = "";
        if (RedisUtil.existKey(key)){
            returnValue = RedisUtil.getCacheObject(key);
        }else {
            String s = sysLabelValueMapper.selectValueBySysIdAndReadOne(id);
            Date endHourByDay = DateUtil.getEndHourByDay(new Date());
            long l = endHourByDay.getTime() - new Date().getTime();
            RedisUtil.setCacheObject(key, s, l, TimeUnit.MILLISECONDS);
            returnValue = s;
        }
        return returnValue;
    }

}
